package com.zero.flutter_gromore_ads.page;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bytedance.sdk.openadsdk.CSJSplashAd;
import com.zero.flutter_gromore_ads.PluginDelegate;
import com.zero.flutter_gromore_ads.R;
import com.zero.flutter_gromore_ads.load.SplashAdLoad;
import com.zero.flutter_gromore_ads.utils.StatusBarUtils;
import com.zero.flutter_gromore_ads.utils.UIUtils;

/**
 * 开屏广告加载模式承接页面
 */
public class AdSplashActivity extends AppCompatActivity {
    private final String TAG = AdSplashActivity.class.getSimpleName();
    // 广告容器
    private FrameLayout ad_container;
    // 自定义品牌 logo
    private AppCompatImageView ad_logo;
    // 是否已展示
    private boolean isShow = false;
    // 开屏广告
    private View splashView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.hideBottomUIMenu(this);
        StatusBarUtils.setTranslucent(this);
        setContentView(R.layout.activity_ad_splash);
        initView();
        initData();
    }

    /**
     * 初始化View
     */
    private void initView() {
        ad_container = findViewById(R.id.splash_ad_container);
        ad_logo = findViewById(R.id.splash_ad_logo);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 获取Logo 参数
        String logo = getIntent().getStringExtra(PluginDelegate.KEY_LOGO);
        // 判断是否有 Logo
        boolean hasLogo = !TextUtils.isEmpty(logo);
        if (hasLogo) {
            // 加载 logo
            int resId = getMipmapId(logo);
            hasLogo = resId > 0;
            if (hasLogo) {
                ad_logo.setVisibility(View.VISIBLE);
                ad_logo.setImageResource(resId);
            } else {
                Log.e(TAG, "Logo 名称不匹配或不在 mipmap 文件夹下，展示全屏");
            }
        }
        // 判断最终的 Logo 是否显示
        if (!hasLogo) {
            ad_logo.setVisibility(View.GONE);
        }
        // 注册接收器和意图过滤器
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter("BR_AdSplashLoadActivity"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        showAd();
    }

    /**
     * 展示广告
     */
    private void showAd() {
        if (isShow) {
            return;
        }
        Log.e(TAG, "showAd");
        isShow = true;

        ad_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                SplashAdLoad splashAdLoad = PluginDelegate.getInstance().splashAdLoad;
                if (splashAdLoad == null) {
                    Log.e(TAG, "广告未加载，请加载后展示");
                    finishPage();
                    return;
                }
                CSJSplashAd gmSplashAd = splashAdLoad.gmSplashAd;
                if (gmSplashAd == null) {
                    Log.e(TAG, "广告未加载成功，请重新加载后展示");
                    finishPage();
                    return;
                }
                // 广告视图设置到 View 上
                splashView = gmSplashAd.getSplashView();
                if (splashView == null) {
                    finishPage();
                    return;
                }
                UIUtils.removeFromParent(splashView);
                ad_container.removeAllViews();
                ad_container.addView(splashView);
            }
        },30);
    }

    /**
     * 完成广告，退出开屏页面
     */
    private void finishPage() {
        Log.d(TAG, "finishPage");
        finish();
        isShow = false;
        // 设置退出动画
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取图片资源的id
     *
     * @param resName 资源名称，不带后缀
     * @return 返回资源id
     */
    private int getMipmapId(String resName) {
        return getResources().getIdentifier(resName, "mipmap", getPackageName());
    }

    // 创建接收器
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "接收到广播");
            // 接收到广播后的操作，例如关闭Activity
            finishPage();
        }
    };

    @Override
    protected void onDestroy() {
        // 不要忘记在onDestroy中注销接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }
}